using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Linq;

namespace RomanJendrusz.Amazon.ETL.Infrastructure.DataBase
{
    public class TableQuerySource<T>: IQuerySource<T> where T:class 
    {
        private readonly Table<T> table;
        private readonly IQueryable<T> queryable;

        public TableQuerySource( Table<T> table)
        {
            this.table = table;
            queryable = table;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<T>) this).GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            return table.GetEnumerator();
        }

        public Expression Expression
        {
            get { return queryable.Expression; }
        }

        public Type ElementType
        {
            get { return queryable.ElementType; }
        }

        public IQueryProvider Provider
        {
            get { return queryable.Provider; }
        }

        public void Add(T item)
        {
            if (table.GetOriginalEntityState(item) == null)
            {
                table.InsertOnSubmit(item);
            }
        }

        public void AddAll(IEnumerable<T> items)
        {
            AssertThat.IsNotNull(items, "items");
            foreach (var item in items)
            {
                Add(item);
            }
        }

        public void Attach(T item)
        {
            table.Attach(item);
        }

        public void Remove(T item)
        {
            table.DeleteOnSubmit(item);
        }

        public void RemoveAll(IEnumerable<T> items)
        {
            table.DeleteAllOnSubmit(items);
        }
    }
}